using Cysharp.Threading.Tasks;
using IQIGame.Onigao.Framework;
using System.Reflection;

namespace IQIGame.Onigao.HotUpdate
{
    public static class HotUpdateEntry
    {
        public static async void Init()
        {
            //执行热更新
            await StartHotUpdate();
            //加载游戏gameplay程序集
            LoadGamePlayAndEnter().Forget();
        }

        public static async UniTask StartHotUpdate()
        {
#if UNITY_EDITOR
            if (!PatchLogicUtility.ActiveEditorPatchLogic)
            {
                return;
            }
            if (!AssetBundleUtility.ActiveBundleMode)
            {
                LogGame.LogWarning($"[{nameof(HotUpdateEntry)}] 开启了编辑器热更模式，但是没有开启编辑器ab模式");
            }
#else
            if (!PatchLogicUtility.ActivePatchLogic)
            {
                return;
            }
#endif

            using (var patchController = new PatchController().Init())
            {
                await patchController.StartPatch();
            }
        }

        /// <summary>
        /// 加载游戏程序集并且进入
        /// </summary>
        public static async UniTaskVoid LoadGamePlayAndEnter()
        {
            // 初始化资源管理器，加载本地ab索引信息
            var resManager = FrameworkEntry.GetModule<ResManager>();
            resManager.InitAssetBundle();

#if UNITY_EDITOR
            if (!HybridCLRUtil.HybridCLREditActive)
            {
                //编辑器反射调用dll
                ReflectionUtility.CallStaticMethod("IQIGameGamePlayAssembly.dll", "IQIGame.Onigao.GamePlay.ProcedureEntry", "EnterGame");
            }
            else
#endif
            {
                //HybridCLR 从ab加载程序集
                ResLoader resloader = ResLoader.Create();
                await LoadHotDlls.LoadMetadataForAOTAssemblies(resloader);

                var usdk = await LoadHotDlls.LoadHotUpdateAssembly(resloader, "IQIGameUSDKAssembly.dll.bytes");
                var frameworkExt = await LoadHotDlls.LoadHotUpdateAssembly(resloader, "IQIGameFrameworkExtAssembly.dll.bytes");
                var gamePlay = await LoadHotDlls.LoadHotUpdateAssembly(resloader, "IQIGameGamePlayAssembly.dll.bytes");
                resloader.Put2Pool();
                if (frameworkExt == null || gamePlay == null || usdk == null)
                {
                    LogGame.LogError("LoadHotDlls.LoadHotUpdateAssembly GamePlays failed!");
                    return;
                }
                var t = gamePlay.GetType("IQIGame.Onigao.GamePlay.ProcedureEntry");
                if (t != null)
                {
                    t.InvokeMember("EnterGame", BindingFlags.InvokeMethod, null, null, null);
                    LogGame.Log("LoadGamePlayAssembly Success!");
                }
                else
                {
                    LogGame.LogError("Not find type GamePlay");
                }
            }
        }
    }
}
